#include "ISprite.h"

int ISprite::ReadInfo()
{
	HRESULT result = D3DXGetImageInfoFromFile(fileName, &info);
	if(result != D3D_OK)
	{
		return 1; // fail
	}
	// Setup sprite info
	this->spriteInfo.columns = SPRITE_COLUMN_N;
	this->spriteInfo.curframe = SPRITE_START_FRAME_INDEX;
	this->spriteInfo.lastframe = SPRITE_COLUMN_N * SPRITE_ROW_N - 1;
	this->spriteInfo.x = SPRITE_X;
	this->spriteInfo.y = SPRITE_Y;
	this->spriteInfo.movex = SPRITE_MOVE_X;
	this->spriteInfo.movey = SPRITE_MOVE_Y;
	this->spriteInfo.width = this->info.Width / SPRITE_COLUMN_N;
	this->spriteInfo.height = this->info.Height / SPRITE_ROW_N;
	return 0; // success
}

void ISprite::Next()
{
	// move sprite
	this->spriteInfo.x += this->spriteInfo.movex;
	this->spriteInfo.y += this->spriteInfo.movey;
	// warp at the edge (only x now)
	if(this->spriteInfo.x + this->spriteInfo.width > GetSystemMetrics(SM_CXSCREEN)) // forward
		this->spriteInfo.x = 0;
	// backward
	if (this->spriteInfo.x < 0)
		this->spriteInfo.x =  GetSystemMetrics(SM_CXSCREEN) - this->spriteInfo.width;

	// change animation
	if(++this->spriteInfo.animatecount >= spriteInfo.animatedelay)
	{
		// reset counter
		this->spriteInfo.animatecount = 0;

		// go to next frame
		this->spriteInfo.curframe++;
		if(this->spriteInfo.curframe > this->spriteInfo.lastframe)
			this->spriteInfo.curframe = SPRITE_START_FRAME_INDEX;
	}
}

RECT* ISprite::GetCurrentRect()
{
	RECT* rect;
	rect = new RECT();
	// Rect is xy not Oxy axis
	rect->left = (spriteInfo.curframe % spriteInfo.columns) * spriteInfo.width;
	rect->top = (spriteInfo.curframe / spriteInfo.columns) * spriteInfo.height;
	rect->right = rect->left + spriteInfo.width;
	rect->bottom= rect->top + spriteInfo.height;
	return rect; // return value
}

ISprite::ISprite(LPWSTR filename = NULL, LPDIRECT3DDEVICE9 d3ddev = NULL, D3DCOLOR transcolor = D3DCOLOR_XRGB(255, 0 ,255))
{
	this->fileName = filename;
	this->transColor = transcolor;
	this->d3ddev = d3ddev;
}

ISprite::ISprite(void)
{
}


ISprite::~ISprite(void)
{
}
